package com.lijian.shiro.realm;

import com.lijian.shiro.entity.User;
import com.lijian.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: LiJian
 * @CreateTime: 2024-12-26
 * Description:
 */

@Component
public class MyRealm2 extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
     return null;
    }

    //自定义登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        String phone = authcToken.getPrincipal().toString();
        // 手机验证码
        // 这里从redis中获取了验证码为 123456，并对比密码是否正确
       //String redisCode = jedisClient.get(phone+"code");
        String redisCode = "123456";
        System.out.println("redisCode------>123456");
        //线上用redisCode取代123456

        User user = userService.findUserByPhone(phone);
        if(user == null){
            throw new UnknownAccountException();
        }
    //第一个参数可以通过SecurityUtils.getSubject().getPrincipal()，相当于用户名
    // 第二个参数相当于数据库中的密码
    // 第三个参数加密的盐（可选添加），第一个参+第二个参组成的用户进行加盐，然后根据realm分配权限。
    // 第四个通过getName()配置，即获取当前realm的名称

        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getPhone(),//数据库中获取的账号
                redisCode,//数据库中获取的密码
                getName()
        );
        return info;

  }
}

